import datetime
import time

from sqlalchemy import Column, Integer, String, ForeignKey, orm
from sqlalchemy.orm import relationship, backref

from app.models.base import db
from app.models.base import Base
from app.models.user import UserModel


class SpaceModel(Base):
    """
    用例组
    """
    __tablename__ = 'space'
    id = Column(Integer, primary_key=True)
    name = Column(String(80), nullable=False, comment='空间名称')
    create_user = Column(Integer, ForeignKey('user.id'))
    user = relationship('UserModel', backref=backref('spaces'))

    @orm.reconstructor
    def __init__(self):
        super(SpaceModel, self).__init__()
        self.fileds = ['id', 'name', 'create_user']

    def keys(self):
        return self.fileds

    @staticmethod
    def add_space(name, create_user):
        with db.auto_commit():
            space = SpaceModel()
            space.name = name
            space.create_user = create_user
            db.session.add(space)

    def get_all_space(self, id=None):
        query = self.query.order_by(getattr(SpaceModel, 'create_time').desc()).filter(SpaceModel.status == 1)
        if id:
            data_list = query.filter(getattr(SpaceModel, 'create_user') == id).all()

        else:
            data_list = query.all()
        return get_spaces(data_list)

    @staticmethod
    def get_all_space_all():
        return len(SpaceModel().query.filter_by().all())

    @staticmethod
    def delete_space(id):
        # 判断是否有权限删除
        # 用户为管理员或者创建者才可删除
        with db.auto_commit():
            s = SpaceModel().query.filter_by(id=id).first_or_404()
            s.delete()
            db.session.commit()

    def get_s_name(self, s_id):
        s = self.query.filter_by(id=s_id).first_or_404()
        return s.name

    @staticmethod
    def search_space(key):
        space_list = SpaceModel().query.filter(SpaceModel.name.like(key)).filter(SpaceModel.status == 1).all()
        return get_spaces(space_list)


def get_len(space):
    num = 0
    for group in space:
        if group.status == 1:
            num += 1
    return num


def get_spaces(spaces):
    s_list = []
    for space in spaces:
        data = dict()
        data['name'] = space.name
        data['len'] = get_len(space.case_groups)
        data['id'] = space.id
        data['owner'] = UserModel().query.filter_by(id=space.create_user).first_or_404().nickname
        data['create_user'] = space.create_user
        data['create_time'] = str(space.create_datetime)
        s_list.append(data)
    return s_list
